﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;

namespace CourseSystem.Common.Helpers
{
    public class PostsAttachHelper
    {
        private static readonly Regex AttachReg = new Regex("(?<=" + CommonHelper.Domain + ")[^\"]*", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>
        /// 清理没有使用的附件,并更新已使用附件的id及随机串置空
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ranStr"></param>
        /// <param name="contentId"></param>
        public static void ClearUselessAttach(string content, string ranStr, int contentId)
        {
            var existList = PostsAttachBLL.GetByExpress(o => o.RanSign == ranStr || o.PostId == contentId);
            if (AttachReg.IsMatch(content))
            {
                var cols = AttachReg.Matches(content);
                var list = (from object item in cols select item.ToString()).ToList();
                var toDelList = new List<PostsAttachInfo>();
                var toUpdate = new List<PostsAttachInfo>();
                foreach (var item in existList)
                {
                    if (list.Contains(item.FileName))
                    {
                        item.PostId = contentId;
                        item.RanSign = "";
                        toUpdate.Add(item);
                    }
                    else
                        toDelList.Add(item);
                }
                PostsAttachBLL.Edit(toUpdate);
                PostsAttachBLL.DelFileByList(toDelList);
            }
            else
            {
                PostsAttachBLL.DelFileByList(existList);
            }
        }

        public static void ClearUselessAttach()
        {
            PostsAttachBLL.DelFileByExpress(
                o => o.PostId == 0 && o.AttachDate.AddDays(1) < DateTime.Now);
        }
    }
}
